<template>
  <view class="waterfall">
    <view v-for="(item, index) in columnData" :key="index" class="column" :style="{ width: columnWidth + 'px' }">
      <view v-for="(childItem, childIndex) in item" :key="childIndex" style="width: 100%" :id="'item' + childItem.id"
            @click="toPersonalArticleDetail(childItem.id)">
        <view class="item" style="background-color:#FFFFFF;margin:10rpx;border-radius:8rpx;">
          <view class="img">
            <base-cover-image :src="childItem?.articleCover" mode="aspectFill"/>
          </view>
          <view class="title-info">
            <view class="item-title">{{ childItem.articleTitle }}</view>
            <view class="item-desc" @click.stop="toPersonalIndex(childItem.userId, childItem.source)">
              <view class="left">
                <view style="width: 50rpx; height: 50rpx;">
                  <base-cover-image :src="childItem?.userPic"/>
                </view>
                <view class="spa">{{ childItem.userName }}</view>
              </view>
              <view class="right" @click.stop="likeCountClick(childItem?.id)">
                <up-icon name="heart" v-if="!childItem?.islike"></up-icon>
                <up-icon name="heart-fill" color="#ff546a" v-else></up-icon>
                <text class="spb">{{childItem.likeCount}}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {
  useArticleStore
} from '../store'
import {
  reactive,
  watch,
  getCurrentInstance,
  ref,
  onMounted
} from 'vue'
import {onShow} from '@dcloudio/uni-app'

const props = defineProps({
  dataList: {
    type: Array,
    required: true,
    default: () => []
  },
  column: {
    type: Number,
    required: true,
    default: 2
  }
})
let columnData = ref([]);
let columnWidth = ref(0);

function debounce(func, delay) {
  let timerId
  return function () {
    clearTimeout(timerId)
    timerId = setTimeout(() => {
      func.apply(this)
    }, delay)
  }
}

watch(
    () => props.dataList,
    debounce((newValue, oldValue) => {
      setColumnWidth()
      setData()
    }, 1000), {
      immediate: true
    },
)

// watch(
// 	() => props.column,
// 	(newValue, oldValue) => {
// 		setColumnWidth()
// 		setData()
// 	}, {
// 		immediate: true
// 	},
// )

function setColumnWidth() {
  // 目前是完整的宽度，如果有padding的需要减去盒子的 padding
  let width = uni.getSystemInfoSync().windowWidth
  columnWidth.value = Math.floor(width / props.column)
}

function toPersonalArticleDetail(id) {
  console.log(id, "| id");
  uni.navigateTo({
    url: `/pages/tab-index/personal/article-details/index?id=${id}`,
  })
}

// 跳转详情
function toPersonalIndex(id, source) {
  uni.navigateTo({
    url: `/pages/tab-index/personal/index?id=${id}&source=${source}`,
  });
}

// 点赞
const articleStore = useArticleStore()

async function likeCountClick(id) {
  await articleStore.articleBehavior({
    id,
    behavior: 1,
    action: 1
  })
  const articleList = articleStore?.articleListData?.objects.find((val) => {
    return val.id === id
  })
  articleList.likeCount = articleList.likeCount + 1
  articleList.islike = true
  uni.showToast({
    title: "点赞成功"
  })
}

function distributeToNArrays(arr, n) {
  let sums = new Array(n).fill(0);
  return arr.reduce(
      (arrays, item) => {
        let minSum = Math.min(...sums);
        let minIndex = sums.indexOf(minSum);
        arrays[minIndex]?.push(item);
        sums[minIndex] += item.itemHeight;
        return arrays;
      },
      new Array(n).fill().map(() => []),
  )
}

function setData() {
  const resultArray = props.dataList.reduce(
      (acc, cur, index) => {
        const targetIndex = index % props.column;
        acc[targetIndex].push(cur);
        return acc;
      },
      Array.from(Array(props.column), () => []),
  );
  console.log(resultArray, "| resultArray");
  columnData.value = resultArray
  getElemHeight()
}

function getElemHeight(index) {
  var arr = [];
  const instance = getCurrentInstance();
  props.dataList.map((item, index) => {
    uni.getImageInfo({
      src: item.articleMainPic,
      success: (e) => {
        item.height = (e.height * (columnWidth.value / e.width)) + 'px'
        arr.push({
          ...{
            itemHeight: item.height
          },
          ...item
        });
        if (arr.length == props.dataList.length) {
          columnData = distributeToNArrays(arr, props.column);
        }
      }
    })
  })
}
</script>

<style lang="scss" scoped>
.waterfall {
  z-index: -1;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.column {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.item {
  overflow: hidden;
}

.title-info {
  padding: 0rpx 20rpx 20rpx 20rpx;
}

.img {
  // height: 386rpx;
  background: #fbfafa;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20rpx;
}

.item-title {
  font-size: 26rpx;
  color: #333333;
  line-height: 46rpx;
  text-align: justify;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  padding: 15rpx 5rpx;
}

.item-desc {
  font-size: 26rpx;
  color: #666666;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .left {
    display: flex;
    align-items: center;

    .spa {
      margin-left: 15rpx;
      font-size: 20rpx;
    }
  }

  .right {
    display: flex;
    align-items: center;

    .spb {
      margin-left: 10rpx;
      font-size: 24rpx;
    }
  }
}
</style>